//
//  HWDownloader.m
//  HomeWork
//
//  Created by apple on 2017/10/26.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HWDownloader.h"
#import "NSString+Extension.h"
#define HWAppImageFile(url) [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]


@interface HWDownloader()
/** 存放所有下载操作的队列 */
@property (nonatomic, strong) NSOperationQueue *queue;
/** 存放所有的下载操作 */
@property (nonatomic, strong) NSMutableDictionary *operations;
@end

@implementation HWDownloader
SingletonM;

- (void)downloadWithUrl:(NSURL *)url completion:(CompletionBlock)completion{
    
    NSString *file = HWAppImageFile(url.absoluteString.md5String);
    // 先从沙盒中取出图片
    NSData *fileData = [NSData dataWithContentsOfFile:file];
    if (fileData) { // 存在
        if (completion) {
            completion([UIImage imageWithData:fileData], nil, url);
        }
        return;
    }
    
    NSBlockOperation *operation = self.operations[url.absoluteString.md5String];
    if (operation) { // 当前操作在队列中
        return;
    }
    operation = [NSBlockOperation blockOperationWithBlock:^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        if (data) { // 请求数据成功
            UIImage *image = [UIImage imageWithData:data];
            if (completion) {
                completion(image, nil, url);
            }
            dispatch_sync(dispatch_get_main_queue(), ^{ // 写入本地
                [data writeToFile:HWAppImageFile(url.absoluteString.md5String) atomically:YES];
            });
        } else { // 错误
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"获取图片错误"                                                                     forKey:NSLocalizedDescriptionKey];
            completion(nil, [NSError errorWithDomain:NSURLErrorDomain code:404 userInfo:userInfo], url);
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            // 从字典中移除下载操作
            [self.operations removeObjectForKey:url.absoluteString.md5String];
        });
        
    }];
    // 添加操作到队列中
    [self.queue addOperation:operation];
     // 添加操作到字典，防止重复下载
    self.operations[url.absoluteString] = operation;
}

- (void)cancelAllDownload{
    
    [self.queue cancelAllOperations];
    [self.operations removeAllObjects];
}

#pragma mark - 懒加载
- (NSOperationQueue *)queue
{
    if (!_queue) {
        _queue = [[NSOperationQueue alloc] init];
        _queue.maxConcurrentOperationCount = 3;
    }
    return _queue;
}

- (NSMutableDictionary *)operations
{
    if (!_operations) {
        _operations = [[NSMutableDictionary alloc] init];
    }
    return _operations;
}


@end
